<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\captcha\Captcha;

class Login extends Controller
{
    /**
     * 首页
     */
    public function index(){
        if (session('?admin_id')) {
            $this->redirect('admin/index/index');
        }
        return $this->fetch('login');
    }

    /**
     * 登录
     */
    public function login()
    {
        $post     = $this->request->post();

        $validate = validate('admin');

        if (!$validate->scene('login')->check($post)) {
            $this->error($validate->getError());
        } else {
            //查询用户
            $user_info = Db::name('admin')
                ->where('username', $post['username'])
                ->find();

            if(!$user_info){
                $this->error('用户不存在');
            }

            if($user_info['status'] != 1){
                $this->error('当前用户禁止登陆');
            }

            if (md5($post['password']) !== $user_info['password']) {
                $this->error('密码错误');
            }

            session('username', $post['username']);
            session('admin_id', $user_info['id']);
//          session('power',$user_info['power']);

            $this->success('登陆成功', '/admin/index/index');

        }
    }
    //验证码
    public function verify()
    {
        $config = [
            'length' => 4,
            'useNoise' => false,
            'bg' => [102, 204, 255]

        ];
        $captcha = new Captcha($config);
        $captcha->codeSet = '0123456789';
        return $captcha->entry();
    }

    //注销
    public function logOut()
    {
        session(null);
        $this->redirect('admin/login/index');
    }
}
